SOLID SRP Example in Python

Problem Statement:

Consider a class Employee that handles both employee information and file operations:

        
class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id

    # ... other properties and methods ...

    def save_to_file(self):
        # logic to save employee details to a file
        pass

    def load_from_file(self):
        # logic to load employee details from a file
        pass
        
    

This violates SRP as the Employee class has multiple reasons to change: one for employee information and another for file operations.

Solution - Applying SRP:

Separate concerns by creating a separate class for file operations:

        
class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id

    # ... other properties and methods ...

class EmployeeFileHandler:
    @staticmethod
    def save_to_file(employee):
        # logic to save employee details to a file
        pass

    @staticmethod
    def load_from_file(employee_id):
        # logic to load employee details from a file
        # return loaded employee object
        pass
        
    

Now, the Employee class focuses solely on employee-related functionality, adhering to the Single Responsibility Principle.

Benefits: